<?php

require_once 'Pipes/ModelList/Grid/ActionBuilder.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model.php';
require_once 'PipesCore/Helpers/Grid/HeaderBuilder.php';
require_once 'PipesCore/Helpers/Grid/BodyBuilder.php';


class Pipes_ModelList_Grid
{
    private $_config    = null;
    private $_modelList = null;
    private $_override  = null;
    
    public function __construct(PipesImpl_Config $config, PipesImpl_ModelList $modelList)
    {
        $this->_config = $config;
        $this->_modelList = $modelList;
        
        $this->_document = new Pipes_Xml_Document();
        $this->_document->appendChild($this->_document->createElement('table'));
    }
    
    public function setOverride($string)
    {
        if (empty($string)) {
            return;
        }
        
        $this->_override = new Pipes_Xml_Document();
        $this->_override->preserveWhiteSpace = false;
        $this->_override->loadXML('<div xmlns:pipes="http://phpinpipes.org/schema/v1">' . $string . '</div>');
    }
   
    public function addHeader() 
    {
        $header = new PipesCore_Helpers_Grid_HeaderBuilder($this->_document);
        $this->_modelList->accept($header);
    }

    public function startBody() {
        $this->_modelList->rewind();
        $body = new PipesCore_Helpers_Grid_BodyBuilder($this->_document);
        $this->_modelList->accept($body);
        ob_start();
    }

    public function addRow(PipesImpl_Model $model) {
       $string = ob_get_clean();
       $capture = new Pipes_Xml_Document();
       $capture->preserveWhiteSpace = false;
       $capture->loadXml('<div xmlns:pipes="http://phpinpipes.org/schema/v1">' . $string . '</div>');

       $rowBuilder = new Pipes_ModelList_Grid_RowBuilder($this->_document, $capture);
       $model->accept($rowBuilder);

        // start output bufferring again
       ob_start();
    }

    public function generate()
    {
        // clear out output buffer from startBody()/addRow()
        ob_end_clean();
        
        $this->_document->documentElement->accept(new Pipes_ModelList_Grid_ActionBuilder($this->_config, $this->_document));
        $this->_document->documentElement->accept(new Pipes_Xml_PipesNsCleaner());
        
        echo $this->_document->render();
    }
}
